package br.com.artsy.library.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import org.hibernate.Session;
import org.springframework.transaction.annotation.Transactional;

import br.com.artsy.library.interfaces.IGenericDAO;
import br.com.caelum.vraptor.ioc.Component;

@Component
public class GenericDAO<T, ID extends Serializable> implements
		IGenericDAO<T, ID> {

	private Session session;
	private final Class<T> persistentClass;

	@SuppressWarnings("unchecked")
	public GenericDAO() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];

	}

	public void setSession(Session session) {
		this.session = session;
	}

	protected Session getSession() {
		return session;
	}

	public Class<T> getPersistentClass() {
		return persistentClass;
	}
	
//	@Transactional
	public void persist(T entity) {
		getSession().persist(entity);
	}

	//@Transactional
	public void save(T entity) {
		getSession().save(entity);
	}

	public void update(T entity) {
		getSession().update(entity);
	}

	public T makePersistent(T entity) {
		getSession().saveOrUpdate(entity);
		return entity;
	}

	public void delete(T entity) {
		getSession().delete(entity);
	}

	@SuppressWarnings("unchecked")
	public T load(ID id) {
		return (T) getSession().get(this.persistentClass, id);
	}
}
